/**
 * 另一个https://github.com/hua1995116/google-translate-open-api/blob/master/README_zh.md
 * 谷歌翻译api。
 * 使用方式：
 * 1、在vue页面导入js文件
 *    import {ggtranslate,gglangs} from '@/common/googletranslate.js';
 * 2、调用方法翻译
 *    ggtranslate("auto","ug","你好").then(r=>{
 *       console.error("翻译结果"+r)
 *       //this.txt=r;
 *    })
 *   
 */
/**
 * @param {Object} fl 原语言，课设为自动，auto，参考语言列表
 * @param {Object} tl 目标语言 ，支持的语言底部语言列表
 * @param {Object} text 带翻译的文本
 */
export  async function ggtranslate(fl, tl, text) {
	//第一步，先从谷歌翻译网页查询tkk值
	const reg = new RegExp("(tkk:')(.*?)(?=')");
	var [error, res] = await uni.request({
		url: 'https://translate.google.cn'
	});
	var tkk = res.data.match(reg)[0].substring(5);
	//console.log(tkk);
	var tk = getTk(text, tkk);
	//第二步实现翻译
	var googleTransUrl = "https://translate.google.cn/translate_a/single?client=t&sl=" + fl + "&tl=" + tl +
		"&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=1&ssel=0&tsel=0&kc=1&tk=" +
		tk + "&q=" + encodeURIComponent(text);
	var [error2, res2] = await uni.request({
		url: googleTransUrl
	})
	var result = res2.data[0][0][0];
	//console.log("翻译结果："+result); 
	return result
}

function b(a, b) {
	for (var d = 0; d < b.length - 2; d += 3) {
		var c = b.charAt(d + 2),
			c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
			c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
		a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
	}
	return a
}
// a:翻译的内容
// TKK:tkk的值
function getTk(a, TKK) {
	for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
		var c = a.charCodeAt(f);
		128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(
			f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] =
			c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
	}
	a = h;
	for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
	a = b(a, "+-3^+b+-f");
	a ^= Number(e[1]) || 0;
	0 > a && (a = (a & 2147483647) + 2147483648);
	a %= 1E6;
	return a.toString() + "." + (a ^ h)
}
/**
 * 支持的语言。更多语言参考https://translate.google.cn
 */
export var gglangs = [{ 
	"key": "zh_CN",
	"value": "简体中文"
}, {
	"key": "en_US",
	"value": "English"
}, {
	"key": "zh_Hant",
	"value": "繁體中文"
}, {
	"key": "ko_KR",
	"value": "韩语"
}, {
	"key": "ja_JP",
	"value": "日本語"
}, {
	"key": "th_TH",
	"value": "ภาษาไทย"
}, {
	"key": "de_DE",
	"value": "Deutsch"
}, {
	"key": "fr_FR",
	"value": "Français"
}, {
	"key": "es_ES", 
	"value": "西班牙语"
}, {
	"key": "it_IT",
	"value": "意大利语"
},{
	"key": "ug",
	"value": "维吾尔语"
}]
